package com.rxz.redisdemo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rxz.redisdemo.common.RedisCommon;
import com.rxz.redisdemo.dao.UserDao;
import com.rxz.redisdemo.entity.Result;
import com.rxz.redisdemo.entity.Users;
import com.rxz.redisdemo.service.RedisServiceImpl;
import com.rxz.redisdemo.utils.RandomUtils;
import com.rxz.redisdemo.utils.ResultUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService extends ServiceImpl<UserDao, Users> implements RedisServiceImpl {

    @Autowired
    private StringRedisTemplate template;

    @Resource(name = "userDao")
    private UserDao userDao;

    @Override
    public Integer incr(Long id) {
        String key = "rxz_info:" + id;
        Long increment = template.opsForValue().increment(key);
        return increment.intValue();
    }


    public Result sendCode(String phone, HttpSession session){
        if(phone.length() != 11){
            return ResultUtil.error(401,"手机号有误！");
        }
        String code = RandomUtils.generateRandomNumberString(6);
        template.opsForValue().set(
                RedisCommon.REIDS_KEY + phone,
                code,
                RedisCommon.REDIS_TTL,
                TimeUnit.MINUTES);

        System.out.println("发送短信认证码成功，认证码为：" + code);
        return ResultUtil.success(code);
    }

    public Result login(String phone,String number,HttpSession session){
        if(phone == null){
            return ResultUtil.error(401,"手机号有误！");
        }
        String cacheCode = template.opsForValue().get(RedisCommon.REIDS_KEY + phone);
        if(cacheCode == null || !cacheCode.equals(number)){
            return ResultUtil.error(401,"验证码错误！");
        }
        String name = userDao.getName(phone);
        String token = UUID.randomUUID().toString();
        String tokenKey = RedisCommon.REIDS_KEY + token;
        Map<String,String> hashMap = new HashMap<>();
        hashMap.put(name,phone);
        template.opsForHash().putAll(tokenKey,hashMap);
        template.expire(tokenKey,RedisCommon.REDIS_TTL,TimeUnit.MINUTES);
        return ResultUtil.success(token);
    }
}
